package com.devgroupvn.dota.youtube;

import java.util.ArrayList;

import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class YoutubeAdapter extends ArrayAdapter<YoutubeData>
{
	ArrayList<YoutubeData> _listSong;
	YoutubeTableCell[] _listCache;
	int _resource;
	Context _context;
	private boolean _isShowAdd;
	ListView _listView;
	boolean _isScroll;
	private int indexNowplaying;

	public YoutubeAdapter(ListView listView, Context context, int textViewResourceId, ArrayList<YoutubeData> objects, boolean isShowAdd)
	{
		super(context, textViewResourceId, objects);
		this._listSong = objects;
		this._context = context;
		this._resource = textViewResourceId;
		this._isShowAdd = isShowAdd;
		_listCache = new YoutubeTableCell[_listSong.size()];
		// _listView = listView;
		// _listView.setOnScrollListener(this);
		// TODO Auto-generated constructor stub
		indexNowplaying = -1;
	}

	public void setNowPlaying(int index)
	{
		indexNowplaying = index;
	}

	@Override
	public int getCount()
	{
		// TODO Auto-generated method stub
		return _listSong.size();
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent)
	{
		convertView = new YoutubeTableCell(_context, _listSong.get(position));
		convertView.setBackgroundColor(Color.WHITE);
		final YoutubeData youtubeData = _listSong.get(position);
		if (youtubeData != null)
		{
			TextView line1 = ((YoutubeTableCell) convertView).line1;
			if (position == indexNowplaying)
			{
				line1.setTextColor(Color.YELLOW);
			}
			TextView line2 = ((YoutubeTableCell) convertView).line2;
			line1.setText(youtubeData.getVideoName());
			YoutubeView youtubeView = ((YoutubeTableCell) convertView).youtubeView;
			if (youtubeData.getThumbnailLink() != null && !_isScroll)
				youtubeView.getImage(youtubeData);
			String strDuration = youtubeData.getDuration() == null ? "0" : youtubeData.getDuration();
			String min="00";
			String sec = "00";
			if(strDuration!=null && !strDuration.contains(":"))
			{
				int dur = Integer.parseInt(youtubeData.getDuration() == null ? "0" : youtubeData.getDuration());
				min = String.valueOf(dur / 60);
				sec = String.valueOf(dur % 60);
				if (youtubeData.getViewCount() != null)
				{
					line2.setText(min + ":" + sec + " - " + youtubeData.getViewCount() + " views");
				}
				else
				{
					line2.setText(min + ":" + sec);
				}
			}
			else if(strDuration!=null)
			{
				line2.setText(strDuration);
			}
			
			_listCache[position] = (YoutubeTableCell) convertView;
			if (position == _listSong.size() - 1)
			{
				View v = ((YoutubeTableCell) convertView).line;
				v.setVisibility(View.VISIBLE);
			}
		}
		return convertView;
	}
}
